//
//  TXFOAuthViewController.swift
//  weibo飞飞
//
//  Created by 田侠飞 on 16/6/25.
//  Copyright © 2016年 田侠飞. All rights reserved.
//

import UIKit
import SVProgressHUD
class TXFOAuthViewController: UIViewController {

    override func loadView() {
        view = webView
    }
    
    
    
    override func viewDidLoad() {
    super.viewDidLoad()
  //创建按钮:

        setupNav()
        
    }
  //设置导航栏按钮
    func setupNav(){
    
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelClick")
     navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFillClick")
    
    navigationItem.title = "OAuth登录"
    
    }
    //按钮点击事件
    @objc private func cancelClick(){
    
    
    dismissViewControllerAnimated(true, completion: nil)
    
    
    }
     //按钮点击事件
    @objc  private func autoFillClick(){
  
  //自动填充:
    
    webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value='995725603@qq.com',document.getElementById('passwd').value='xiafei0404'")
        
        
        
    }
    
    //创建webView
    
    private lazy  var webView : UIWebView = {
    let view = UIWebView()
        
        
        view.delegate = self
//    d6962d47971d1c3c5536f16d12bfebd8
        let  APPKEY = "3517187157"
        let REDIRECT_URI = "http://www.baidu.com"
    let  url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")!
    
      
        
        
    let  request = NSURLRequest(URL: url)
        
    view.loadRequest(request)
        
    
    return view
    }()

}
extension TXFOAuthViewController :UIWebViewDelegate{
//开始下载
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
  //持续加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString
       
        if let u = urlString where u.hasPrefix(REDIRECT_URI){
        
         
        let query = request.URL?.query
            
   
        
//            http://www.baidu.com/?code=bbe8c19fef146924d3cdd175f520cbe5
//            Optional("code=bbe8c19fef146924d3cdd175f520cbe5")
//截取字符串
            
            if let q =  query {
            
            
            let code  = q.substringFromIndex("code=".endIndex)
                
             loadUserAccount(code)
                
               
             
            print("这是code码\(code)")
                
              return false
            
            }
        
        
        
        }
        
        
        return true
        
    }
    
    //加载失败(打印错误)
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
      print(error)
    }
    
    //完成加载
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }


}

extension TXFOAuthViewController{
   func loadUserAccount(code:String){
    
    TXFNetworkTools.shareTools.oauthLoadUserAccount(code, success: { (response) -> () in
        
        print(response)
        
        
    guard  let res  = response as? [String: AnyObject] else  {
    
   
    return
    
    }
    //字典转模型:
    let  userAccount = TXFUserAccount(dict: res)
    self.loadUserInfoAccount(userAccount)
    print(userAccount)
    
    }) { (error) -> () in
        
        print("出错了")
        print(error)
        }
    
    
    }

    func loadUserInfoAccount(userAccount : TXFUserAccount){
    
    TXFNetworkTools.shareTools.oauthLoadUserInfo(userAccount, success: { (response) -> () in
        
        guard let res = response as? [String: AnyObject] else{
            
        return
        }
        
        //字典转模型
        
        //let userAccount = TXFUserAccount(dict: res)
        
        userAccount.avatar_large = res["avatar_large"]as? String
        userAccount.screen_name = res["screen_name"]as? String
        //保存数据
        
        TXFUserAccountTools.sharedTools.saveUserAccount(userAccount)
        
       
        print(TXFUserAccountTools.sharedTools.userAccount)
        //登录之后要销毁当前的控制器
 self.dismissViewControllerAnimated(false, completion: { () -> Void in
            //通过通知方式来
            NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVcNotification, object: nil)
            
        })
        
        }) { (error) -> () in
            
        }
 
    }

}